//
//  AppDelegate.m
//  NetPhone
//
//  Created by intel intel on 12-4-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "GlobalVar.h"
#import "ViewController.h"
#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import "iToast.h"
#import "MainViewController.h"
#import "HttpFeedBack.h"
#import "XMLReader.h"
#import "GDataXMLNode.h"
#import "GlobalVar.h"

//
@implementation AppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize loginNav;

//
- (void)dealloc
{
    [_window release];
    [_viewController release];
    [loginNav release];
    [super dealloc];
}
//弹出更新对话框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 200)
    {
        exit(0);
    }else
    {
        if (buttonIndex == 0)
        {
            NSURL *xurl = [[[NSURL alloc]initWithString:[NSString stringWithFormat:@"itms-apps://itunes.apple.com/us/app/id%@?mt=8",APP_ID]]autorelease];
            [[UIApplication sharedApplication] openURL:xurl];
        }
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.blnFirstOpenApp=YES;
    [GlobalVar createEditableDataBaseIfNeeded];
    [SocketDispatch sharedInstance].delegate=self;
    [[SocketDispatch sharedInstance] socketCheck];
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    MainViewController* main=[[[MainViewController alloc]init]autorelease];
    //main.delegate=self;
    self.window.rootViewController=main;
    [self.window makeKeyAndVisible];
    //
    return YES;
}
-(void)checkTheBestIpComplete
{
    //NSLog(@"====checkTheBestIpComplete=====");
    if (self.blnFirstOpenApp==YES)
    {
        self.blnFirstOpenApp = NO;
        //请求初始化数据
        [self getAllInfro:@"1"];
        
    }
}
-(void)enterSoft
{
    //查看是否把手机号邦定了？
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_NUMBER"])
    {
        [self bandingSuccess];
    }else
    {
        [self logout];
    }
}

-(void)bandingSuccess
{
    NSLog(@"======bandingSuccess=邦定成功，进入主界面=====");
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
}
//========邦定界面=========
-(void)logout
{
    NSLog(@"======logout====邦定界面==");
    BangDing_ViewControl* bdv=[[[BangDing_ViewControl alloc]init]autorelease];
    bdv.delegate=self;
    self.loginNav=[[[UINavigationController alloc]initWithRootViewController:bdv]autorelease];
    self.window.rootViewController=self.loginNav;
}



//请求初始化数据
-(void)getAllInfro:(NSString*)blnProxy
{
    //NSLog(@"==========请求初始化界面数据====");
    NSString* prePare=[NSString stringWithFormat:@"%@%@%@%@",SOFT_ID,[GlobalVar getTheCertNum],@"iphone",@"ysw"];
    NSString* md5=[GlobalVar md5Str:prePare];
    NSString* CanShu=[NSString stringWithFormat:@"<request><productid>%@</productid><agentid>%@</agentid><platform>iphone</platform><md5>%@</md5></request>",SOFT_ID,SOFT_ID,md5];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:[GlobalVar getFinalExtaUrl]]];
    [request setDelegate:self];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    [request setUsername:blnProxy];
    if ([blnProxy isEqualToString:@"1"])
    {
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }
    [request setPostBody:[NSMutableData dataWithData:[CanShu dataUsingEncoding:NSUTF8StringEncoding]]];
    [request setDidFinishSelector:@selector(requestAllInfroSuccess:)];
    [request setDidFailSelector:@selector(requestAllInfroError:)];
    [request startAsynchronous];
    
}

//获取失败
-(void)requestAllInfroError:(ASIHTTPRequest*)request
{
    NSLog(@"====requestAllInfroError====");
    if ([request.username isEqualToString:@"1"])
    {
        //请求初始化数据 用转页面处理试一试
        [self getAllInfro:@"2"];
    }else
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接超时" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertView.tag=200;
        [alertView show];
    }
    
}
//返回 初始化 数据
-(void)requestAllInfroSuccess:(ASIHTTPRequest*)request
{
    //NSLog(@"===初始化 数据==username==%@",request.username);
    if ([request.username isEqualToString:@"1"])
    {
        [GlobalVar sharedInstance].blnUseProxy= YES;
    }else
    {
        [GlobalVar sharedInstance].blnUseProxy= NO;
    }
    NSString* str=[request responseString];
    //NSLog(@"返回 初始化 数据===:%@ \n",str);
    //& 特别符号处理
    str = [str stringByReplacingOccurrencesOfString:@"&" withString:@"$"];
    if ([str length]>0)
    {
        if ([str rangeOfString:@"<rcode>0</rcode>"].location!=NSNotFound)
        {
            NSError *parseError = nil;
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            if (parseError)
            {
                NSLog(@"parseError=====%@",parseError.debugDescription);
                return;
            }
            NSUserDefaults* defaults1=[NSUserDefaults standardUserDefaults];
            [defaults1 setObject:EXTA_INTERFACE_URL forKey:@"FINALKUOZHANURL"];//并发路径
            [defaults1 synchronize];
            NSString* kefuCall = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"phone"]valueForKey:@"text"];
            //NSLog(@"客服电话是：%@",kefuCall);
            NSString* tempVipUrl = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"vipurl"]valueForKey:@"text"];;
            NSString* vipName=@"";
            NSString* vipUrl=@"";
            if (![tempVipUrl isEqualToString:@""])
            {
                NSArray* array=[tempVipUrl componentsSeparatedByString:@"@"];
                vipName=[array objectAtIndex:0];
                //NSLog(@"名字是::%@",vipName);
                vipUrl=[array objectAtIndex:1];
                vipUrl = [vipUrl stringByReplacingOccurrencesOfString:@"$" withString:@"&"];
                //NSLog(@"会员地址是:%@",vipUrl);
            }
            NSString* contentTuijian = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"share"]valueForKey:@"text"];
            //NSLog(@"推荐好友::%@",contentTuijian);
            NSString* webAdd = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"officeweb"]valueForKey:@"text"];
            //NSLog(@"官网地址::%@",webAdd);
            NSString* recStr = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"recharge"]valueForKey:@"text"];
            //NSLog(@"第三方充值功能::%@",recStr);
            NSString* baoyueSwitch = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"baoyue"]valueForKey:@"text"];
            //NSLog(@"包月开关::%@",baoyueSwitch);
            NSString* openFlow = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"openFlow"]valueForKey:@"text"];
            //是否开启 兑换流量
            NSString* changeFlow = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"changeFlow"]valueForKey:@"text"];
            //
            NSString* scrollContentSwitch = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"subtitle"]valueForKey:@"text"];
            //NSLog(@"滚动字幕开关::%@",scrollContentSwitch);
            NSString* feedbackSwitch = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"feedback"]valueForKey:@"text"];
            //NSLog(@"意见反馈开关::%@",feedbackSwitch);
            NSString* qrCodeStr = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"qrcode"]valueForKey:@"text"];
            //
            NSString* agentAdStr = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"agentAd"]valueForKey:@"text"];
            //NSLog(@"二级代理商广告::%@",agentAdStr);
            NSString* multiAgentStr = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"multiAgent"]valueForKey:@"text"];
            // NSLog(@"代理商限制::%@",multiAgentStr);
            NSString* showMinStr = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"showMin"]valueForKey:@"text"];
            //NSLog(@"是否显示分钟::%@",showMinStr);
            NSString* rate = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"rate"]valueForKey:@"text"];
            //NSLog(@"费率::%@",rate);
            NSString* isUpdateFile = [[[xmlDictionary valueForKey:@"Root"]valueForKey:@"uploadlog"]valueForKey:@"text"];
            //NSLog(@"是否上传文件::%@",isUpdateFile);
            NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
            [defaults setObject:kefuCall  forKey:@"kefuCall"];
            [defaults setObject:vipName forKey:@"vipName"];
            [defaults setObject:vipUrl forKey:@"vipUrl"];
            [defaults setObject:isUpdateFile forKey:@"UPDATEFILE"];
            [defaults setObject:contentTuijian forKey:@"tuijianContent"];
            [defaults setObject:webAdd forKey:@"webAdd"];
            [defaults setObject:baoyueSwitch forKey:@"baoyueOrLiuliang"];
            if ([baoyueSwitch isEqualToString:@"1"])//1表示包月，0表示显示余额
            {
                NSString* content=[[[xmlDictionary valueForKey:@"Root"]valueForKey:@"bycontent"]valueForKey:@"text"];
                //NSLog(@"内容是::%@",content);
                [defaults setObject:content forKey:@"CONTENT"];
            }
            [defaults setObject:scrollContentSwitch forKey:@"showScrollOrNot"];
            [defaults setObject:agentAdStr forKey:@"agentAd"];
            [defaults setObject:multiAgentStr forKey:@"multiAgent"];
            [defaults setObject:showMinStr forKey:@"showMin"];
            [defaults setObject:recStr forKey:@"recStr"];
            [defaults setObject:openFlow forKey:@"openFlow"];
            [defaults setObject:rate forKey:@"rate"];
            [defaults setObject:qrCodeStr forKey:@"qrCodeStr"];
            [defaults setObject:changeFlow forKey:@"changeFlow"];
            [defaults synchronize];
            NSString* urls=[[[xmlDictionary valueForKey:@"Root"]valueForKey:@"transitAddress"]valueForKey:@"text"];
            if ([urls length]>0)
            {
                NSArray* urlsArr=[urls componentsSeparatedByString:@"|"];
                if ([urlsArr count]>0)
                {
                    [self createTheZhongzhuanUrlsFile:urlsArr];
                }
                //NSLog(@"urlsAr+r======%@",urlsArr);
            }
        }
    }
    //获取过场界面图片 获取过场界面图片 3
    [self requestForLauchAdv];
    [GlobalVar writeTheInfoToTheLocal:@"启动\n"];
    [GlobalVar writeTheInfoToTheLocal:[NSString stringWithFormat:@"%d\n",[GlobalVar getCarrierNetWorkSignal]]];
    //
    [self performSelector:@selector(enterSoft) withObject:nil afterDelay:2.0f];
    
}
#pragma 获取过场界面图片数据
-(void)requestForLauchAdv
{
    //NSLog(@"===获取过场界面图片====");
    _httpAgent=[[HttpForAgent alloc]init];
    _httpAgent.delegate=self;
    [_httpAgent requestData:@"3" setUsername:GetLaunchView];
}
//返回场界面图片数据
-(void)requestLuanchViewSuccess:(NSString*)str
{
    //NSLog(@"获取过场界面数据=====:%@ \n",str);
    NSError *parseError = nil;
    NSDictionary *nsDicData = [XMLReader dictionaryForXMLString:str error:&parseError];
    if (parseError)
    {
        NSLog(@"parseError=====%@",parseError.debugDescription);
        return;
    }
    NSDictionary *xmlDictionary = [[nsDicData valueForKey:@"root"]valueForKey:@"ret"];
    NSString* code = [[xmlDictionary valueForKey:@"code"]valueForKey:@"text"];
    if ([code isEqualToString:@"0"])
    {
        NSString* nsStrUrl=[[xmlDictionary valueForKey:@"url0"]valueForKey:@"text"];
        NSString* total_Lau_Im=[NSString stringWithFormat:@"%@%@",HTTP,nsStrUrl];
        //获取过场界面
        NSString* saveImgStatus=[[NSUserDefaults standardUserDefaults] objectForKey:@"saveImgStatus"];
        if (saveImgStatus.length==0 || ![saveImgStatus isEqualToString:total_Lau_Im])
        {
            [NSThread detachNewThreadSelector:@selector(loadLauch:) toTarget:self withObject:total_Lau_Im];
            //NSLog(@"获取过场界面图片地址:::%@",total_Lau_Im);
        }
    }
}
//获取失败
-(void)requestError:(ASIHTTPRequest*)request
{
    NSLog(@"获取失败=username=%@  Error====%@",request.username,[request error]);
}
//加载过场界面图片
-(void)loadLauch:(NSString*)url
{
    NSURL* LauchUrl=[NSURL URLWithString:url];
    NSData* LauchData=[NSData dataWithContentsOfURL:LauchUrl];
    if (LauchData!=nil)
    {
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        //记录图片路径
        [defaults setObject:url forKey:@"saveImgStatus"];
        //保存图片
        [defaults setObject:LauchData forKey:@"launchData"];
        [defaults synchronize];
    }
}

-(NSString*)NSScanner:(NSString*)str
{
    NSScanner* scanner=[NSScanner scannerWithString:str];
    NSString* text=nil;
    while ([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"\\n" intoString:nil];
        [scanner scanUpToString:@"\n" intoString:&text];
        str=[str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",text] withString:@""];
        str=[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        str=[str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        str=[str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    return str;
}
-(void)applicationProtectedDataDidBecomeAvailable:(UIApplication *)application
{
    NSLog(@"===applicationProtectedDataDidBecomeAvailable===");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSLog(@"=====结束时间=====");
    NSString* QBKey = [[NSUserDefaults standardUserDefaults]objectForKey:@"QBKey"];
    if (QBKey && [QBKey rangeOfString:@"QB"].location!=NSNotFound)
    {
        NSInteger endTime=[[NSDate date]timeIntervalSince1970];
        NSString*nsStrEndTime=[NSString stringWithFormat:@"%ld",(long)endTime];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:nsStrEndTime forKey:@"endTime"];
        [userDefaults synchronize];
        NSString *nsStrStarTime=(NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"starTime"];
        NSInteger starTime= [nsStrStarTime integerValue];
        NSUInteger time=endTime-starTime;
        //提交通话记录
        [self submitCallingTime:QBKey callingTime:[NSString stringWithFormat:@"%d",time]];
    }
    if ([ViewController sharedInstance])
    {
        [[ViewController sharedInstance] dismissModalViewControllerAnimated:NO];
    }
    
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"applicationWillResignActive");
    NSString* QBKey = [[NSUserDefaults standardUserDefaults]objectForKey:@"QBKey"];
    if (QBKey && [QBKey rangeOfString:@"QB"].location!=NSNotFound)
    {
        NSInteger starTime = [[NSDate date]timeIntervalSince1970];
        NSString*nsStrStarTime=[NSString stringWithFormat:@"%ld",(long)starTime];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:nsStrStarTime forKey:@"starTime"];
        [userDefaults synchronize];
    }
    
}
//创建保存中转地址文件
-(void)createTheZhongzhuanUrlsFile:(NSArray*)arr
{
    NSString* fullPath=[GlobalVar getFilePath:@"zhongzhuanUrl.plist"];
    // NSLog(@"the zhongzhuanUrl:%@",fullPath);
    [arr writeToFile:fullPath atomically:YES];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{

    NSLog(@"=====applicationDidEnterBackground=====");
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSLog(@"=====applicationWillEnterForeground=====");
}




- (void)applicationWillTerminate:(UIApplication *)application
{

    
    NSLog(@"=====applicationWillTerminate=====");
}
//提交通话记录
-(void)submitCallingTime:(NSString *)QBKey callingTime:(NSString *)time
{
    NSLog(@"提交通话记录====%@  time= %@",QBKey,time);
    //NSString *QBKey = @"QB201505312232521311019";
    //NSString *second = @"50";
    NSString* prepareMD5=[NSString stringWithFormat:@"%@%@%@",QBKey,time,@"k23j4o8"];
    NSString* md5Str=[GlobalVar md5Str:prepareMD5];
    ASIFormDataRequest* request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://121.40.86.219:8008/callback.php"]];
    [request setDelegate:self];
    [request setTimeOutSeconds:30.0f];
    [request setPostValue:time forKey:@"second"];
    [request setPostValue:QBKey forKey:@"key"];
    [request setPostValue:@"iphone" forKey:@"type"];
    [request setPostValue:md5Str forKey:@"md5"];
    [request setPostValue:SOFT_VER forKey:@"version"];
    [request setPostValue:SOFT_ID forKey:@"softid"];
    [request setDidFinishSelector:@selector(submitCallingTimeSuccess:)];
    [request setDidFailSelector:@selector(submitCallingTimeFail:)];
    [request startAsynchronous];
}
-(void)submitCallingTimeSuccess:(ASIHTTPRequest*)request
{
    NSLog(@"提交通话记录 返回 ：%@",[request responseString]);
}
-(void)submitCallingTimeFail:(ASIHTTPRequest*)request
{
    NSLog(@"提交通话记录 fail ：%@",[request responseString]);
}

@end
